package dao;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import model.reservation.teacher.Reservation;
import model.teacher.Teacher;

import parsers.CommonMethods;
import parsers.reservation.ReservationTParser;

public class ReservationTDAO 
{
	private static Map<String, Reservation> reservationCP = new HashMap<String, Reservation>();
	
	private static String currentDate = util.Utilities.getDateTime();
	
	private static String file = makeFileName("resCP");
	
	private long startTime;
	
	@SuppressWarnings("unchecked")
	public ReservationTDAO()
	{
		startTime();
		System.out.print("Initialising ReservationTDAO->Reservation: ");
		if( (new File(file)).exists() )
		{
			System.out.print("(find serialized file " + file + ") ");
			reservationCP = (Map<String, Reservation>) util.Utilities.deserialize(file);
		}
		else
		{
			initReservationTSchedule();
		}
		System.out.println(countTime() + " ms");
	}
	
	private static String makeFileName(String name)
	{
		return Linker.path + ReservationTDAO.class.getName() + name + currentDate + ".jsr";
	}
	
	public static void serialize()
	{
		if( !(new File(file)).exists() )
		{
			util.Utilities.serialize(reservationCP, file);
		}
	}
	
	private void initReservationTSchedule()
	{
		Iterator<Teacher> teachers = TeacherDAO.getTeachersScheduleCP().values().iterator();
		while(teachers.hasNext())
		{
			Teacher teacher = teachers.next();
			
			Reservation reservation = new Reservation(teacher.getName(), teacher.getUnit());
			reservation.setId(teacher.getId());
			reservation.setLink(CommonMethods.parseLink(teacher.getLink()) + "&pTyp=R");
			
			try
			{
				ReservationTParser lrp = new ReservationTParser(reservation);
				lrp.parse();
				reservationCP.put(reservation.getId(), reservation);
			} 
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	public static Map<String, Reservation> getReservationCP()
	{
		return reservationCP;
	}
	
	private void startTime()
	{
		startTime = System.currentTimeMillis();
	}
	
	private long countTime()
	{
		return System.currentTimeMillis() - startTime;
	}
}